package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendMsg(String phone) {
        //1.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //测试阶段先写成123
        code = "123"; //TODO
        // 2.发送sms短信
        // smsTemplate.sendSms(phone, code); // TODO 开发期间不发送短信
        // 3.将验证码存入redis
        redisTemplate.opsForValue().set("code:" + phone, code, Duration.ofSeconds(300));

    }

    @Override
    public ResultInfo login(String phone, String code) {
        //1.校验验证码
        //先取出code
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:" + phone);
        //如果验证码不同就登陆失败
        if (!StrUtil.equals(code,codeFromRedis)) {
            throw new CustomException("验证码不正确");
        }
        //2.根据手机号查询
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, phone);
        User user = userMapper.selectOne(qw);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }else {
            if (user.getStatus()!= 1) {
                throw new CustomException("您的账户已被封禁，请联系警局解决");
            }
        }
        //通过jwt制作token
        Map claims = new HashMap();
        claims.put("id", user.getId());
        claims.put("phone",user.getPhone());
        String token = JwtUtil.createToken(claims);
        //redis存储对象
        redisTemplate.opsForValue().set("phone:" + user.getPhone(), user, Duration.ofDays(1));
        //5.清理验证码
        redisTemplate.delete("code:" + phone);
        //返回token
        return ResultInfo.success(token);
    }

    @Override
    public void logout() {
        redisTemplate.delete("phone");

    }
}
